package com.naizhuai.ui.mianbusiness.action;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.business.ActionAddImageAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionBrightPointImageAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionImageBrightPointProcessAdapterHolder;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.entity.ImageBean;
import com.naizhuai.ui.entity.SimpleKeyValueBean;
import com.naizhuai.ui.entity.mainbusiness.ActionBaseBean;
import com.naizhuai.ui.entity.mainbusiness.ActionCompareDataBean;
import com.naizhuai.ui.entity.mainbusiness.ActionEditContractActivityBean;
import com.naizhuai.ui.entity.mainbusiness.ActionSelectedProcessImageDetails;
import com.naizhuai.ui.entity.mainbusiness.CompareImageBean;
import com.naizhuai.ui.loopviewpager.AutoLoopViewPager;
import com.naizhuai.ui.mianbusiness.action.presenter.ActionManageApiStoreIml;
import com.naizhuai.ui.mianbusiness.presenter.PublicDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.PersonRadarActivity;
import com.naizhuai.ui.task.ActionSetting1Activity;
import com.naizhuai.ui.viewpagerindicator.CirclePageIndicator;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ErrorViewCreateUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.MathUtils;
import com.naizhuai.util.NaizhuAILog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;


/**
 * 行为提交之后的浏览界面
 */
public class ActionBeforeExamineDetailsActivity extends BaseActivity implements View.OnClickListener, ActionBrightPointImageAdapterHolder.OnItemClickListener {
    private static final String TAG = "ActionBrightSpotActivity";

    private String actionId;

    //行为标题
    @BindView(R.id.action_name)
    TextView actionName;
    @BindView(R.id.user_name)
    TextView chargeName;
    @BindView(R.id.user_thumb)
    CircleImageView circleThumb;

    //展示合成图片内容
    @BindView(R.id.edit_pager)
    AutoLoopViewPager editPager;
    @BindView(R.id.pager_indicator)
    CirclePageIndicator magicIndicator;
    private List<ImageBean> mergeImageList;
    private EditContractPagerAdapter targetAdapter;

    //详情
//    @BindView(R.id.action_details_txt)
//    TextView actionDetails;

    //分析
    @BindView(R.id.analysis_txt)
    RecyclerView analysisRecy;
    List<String> analysisList;
    private ActionImageBrightPointProcessAdapterHolder analysisAdapter;
    @BindView(R.id.analysis_layout)
    CardView analysisLayout;

    //过程数据以及图片
    @BindView(R.id.process_lines_txt)
    RecyclerView recyclerProTxt;
    @BindView(R.id.process_images)
    RecyclerView recyclerProImg;
    private List<String> processStr;
    private List<String> processImg;
    @BindView(R.id.process_details_layout)
    CardView processLayout;

    private ActionSelectedProcessImageDetails imageDetails;
    //过程图片+过程描述的adapter
    private ActionBrightPointImageAdapterHolder imageContentAdapter;
    private ActionImageBrightPointProcessAdapterHolder detailsAdapter;

    //心得
    @BindView(R.id.experience_layout)
    CardView experienceCard;
    @BindView(R.id.action_experience)
    TextView actionExperience;

    //数据展示
    @BindView(R.id.compare_data_card)
    CardView compareDataCard;
    @BindView(R.id.before_data)
    TextView preData;
    @BindView(R.id.after_data)
    TextView aftData;
    @BindView(R.id.improve_ratio)
    TextView proRatio;
    @BindView(R.id.improve_money)
    TextView proMoney;

    @BindView(R.id.error_content)
    RelativeLayout errorLayout;

    private ActionEditContractActivityBean editActivityBean;
    private Subscription brightSpotSub;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
//        initErrorBitmap();
        initBaseView();
        requestData();
    }

    private void requestData() {
        initErrorLayout();
        getFromRequest();
    }

    private void initErrorLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        errorLayout.removeAllViews();
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(this));
    }

    private void initBaseView() {
        initBaseBtn();
        recyclerProImg.post(new Runnable() {
            @Override
            public void run() {
                initRecyclerView();
            }
        });
    }

    private void initRecyclerView() {
        //过程分析数据
        analysisAdapter = new ActionImageBrightPointProcessAdapterHolder(this, analysisList);
        analysisRecy.setNestedScrollingEnabled(false);
        analysisRecy.setHasFixedSize(true);
        analysisRecy.setLayoutManager(new LinearLayoutManager(this));
        analysisRecy.setItemAnimator(new DefaultItemAnimator());
        analysisRecy.setAdapter(analysisAdapter);
        //图片选择的横向的recyclerView
        imageContentAdapter = new ActionBrightPointImageAdapterHolder(this, processImg, recyclerProImg.getWidth());
        recyclerProImg.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerProImg.setLayoutManager(layoutManager);
        recyclerProImg.setItemAnimator(new DefaultItemAnimator());
        recyclerProImg.setAdapter(imageContentAdapter);
        imageContentAdapter.setOnItemClickListener(this);
        //图片描述的纵向RecyclerView
        detailsAdapter = new ActionImageBrightPointProcessAdapterHolder(this, processStr);
        recyclerProTxt.setNestedScrollingEnabled(false);
        recyclerProTxt.setHasFixedSize(true);
        recyclerProTxt.setLayoutManager(new LinearLayoutManager(this));
        recyclerProTxt.setItemAnimator(new DefaultItemAnimator());
        recyclerProTxt.setAdapter(detailsAdapter);
    }

    private void initEditPager() {
        editPager.getLayoutParams().height = editPager.getWidth();
        targetAdapter = new EditContractPagerAdapter(this, mergeImageList);
        editPager.setAdapter(targetAdapter);
//        initIndicator();
        magicIndicator.setViewPager(editPager);
        magicIndicator.setPadding(5, 5, 10, 15);
    }

    private void initBaseBtn() {
    }

    private void initBaseData() {
        mergeImageList = new ArrayList<>();
        analysisList = new ArrayList<>();
        processStr = new ArrayList<>();
        processImg = new ArrayList<>();
        imageDetails = new ActionSelectedProcessImageDetails();
        Bundle bundle = getIntent().getExtras();

        if (bundle != null)
            actionId = bundle.getString(ActionBaseBean.ACTION_ID_KEY);
    }

    private void getFromRequest() {
        brightSpotSub = ActionManageApiStoreIml.getInstance().getActionBeforeDetals(actionId).subscribe(new Observer<ActionEditContractActivityBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                NaizhuAILog.e("e=" + e.getMessage());
                errorLayout.setVisibility(View.VISIBLE);
                errorLayout.removeAllViews();
                errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> {
                    initErrorLayout();
                    requestData();
                }));
            }

            @Override
            public void onNext(ActionEditContractActivityBean actionEditContractActivityBean) {
                errorLayout.removeAllViews();
                if (actionEditContractActivityBean != null) {
                    errorLayout.setVisibility(View.INVISIBLE);
                    editActivityBean = actionEditContractActivityBean;
                    refreshData();
                } else {
                    errorLayout.setVisibility(View.VISIBLE);
                    errorLayout.addView(ErrorViewCreateUtils.createEmptyView(getActivityContext()));
                }
            }
        });
    }


    //更新数据
    private void refreshData() {
        createTxtData();
        changeImageData();
    }

    private void changeImageData() {
        List<SimpleKeyValueBean> showImage = new ArrayList<>();
        for (String img : processImg) {
            showImage.add(new SimpleKeyValueBean(ActionAddImageAdapterHolder.URL_NET_IMAGE, img));
        }
        imageDetails.setImageList(showImage);
    }

    private void createTxtData() {
        //更新题目
        actionName.setText(editActivityBean.getQuestionTitle());
        chargeName.setText(editActivityBean.getUsername());
        ImageUtils.glideThumbViewByUrl(this, circleThumb, editActivityBean.getThumb());
        chargeName.setText(editActivityBean.getUsername());

        //更新合成图片
        mergeImageList.clear();
        for (CompareImageBean imageBean : editActivityBean.getCompareImage()) {
            mergeImageList.add(imageBean.getMergeImage());
        }
        initEditPager();
        //分析
        analysisList.clear();
        analysisList.addAll(ListUtils.removeEmpty(editActivityBean.getThinkingDetail()));
        analysisAdapter.notifyDataSetChanged();
        if (analysisList.size() > 0)
            analysisLayout.setVisibility(View.VISIBLE);
        else
            analysisLayout.setVisibility(View.GONE);
        //过程数据
        processStr.clear();
        processStr.addAll(ListUtils.removeEmpty(editActivityBean.getProcessDetail()));
        detailsAdapter.notifyDataSetChanged();
        processImg.clear();
        processImg.addAll(editActivityBean.getProcessImages());
        imageContentAdapter.notifyDataSetChanged();
        if (processStr.size() > 0 || processImg.size() > 0)
            processLayout.setVisibility(View.VISIBLE);
        else
            processLayout.setVisibility(View.GONE);

        //心得
        if (!TextUtils.isEmpty(editActivityBean.getReview()))
            actionExperience.setText(editActivityBean.getReview());
        else
            experienceCard.setVisibility(View.GONE);
        int scoreNumber = Integer.parseInt(editActivityBean.getScore());

        //数据结构体
        if (editActivityBean.getSelectedCompareData() != null && editActivityBean.getSelectedCompareData().size() > 0 && !TextUtils.isEmpty(editActivityBean.getSelectedCompareData().get(0).getPointId())) {
            ActionCompareDataBean compareDataBean = editActivityBean.getSelectedCompareData().get(0);
            //金額的占位String
            String valueNumber = getText(R.string.action_compare_data).toString();
            String radiuNumber = getText(R.string.improve_ratio_data).toString();
            String moneyNumber = getText(R.string.improve_money_data).toString();
            String pre = compareDataBean.getbValue();
            String after = compareDataBean.getaValue();
            String afterValue = String.format(valueNumber, after, compareDataBean.getUnit());
            aftData.setText(afterValue);
            String preValue = String.format(valueNumber, pre, compareDataBean.getUnit());
            preData.setText(preValue);
            String ratio = MathUtils.numberRadius(pre, after);
            if (ratio != null) {
                proRatio.setText(String.format(radiuNumber, ratio, getString(R.string.percent)));
            } else
                proRatio.setText(getText(R.string.error_data));
            proMoney.setText(String.format(moneyNumber, compareDataBean.getSimulatedAmount()));
        } else
            compareDataCard.setVisibility(View.GONE);

    }

    @OnClick({R.id.back_icon})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_icon:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onBackPressedWithoutDialog() {
        if (brightSpotSub != null && !brightSpotSub.isUnsubscribed()) {
            DialogUtils.showSureDialog(this, getString(R.string.cancel_submit_request), new View.OnClickListener() {
                @Override
                public void onClick(View dialog) {
                    brightSpotSub.unsubscribe();
                }
            });
        } else {
            super.onBackPressedWithoutDialog();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_business_action_before_examine_scan_layout;
    }

    @Override
    public void onItemClick(View view, int position) {
        imageDetails.setPosition(position);
        imageDetails.setEdit(false);
        IntentUtils.startActivityWithObject(ActionShowChoseImageActivity.IMAGE_DATA_DETAILS, imageDetails, this, ActionShowChoseImageActivity.class);
    }

    //轮播图适配器
    private class EditContractPagerAdapter extends PagerAdapter {
        private BaseActivity mContext;
        private List<ImageBean> editImage;

        EditContractPagerAdapter(BaseActivity context, List<ImageBean> editImage) {
            this.mContext = context;
            this.editImage = editImage;
        }

        @Override
        public int getCount() {
            return editImage.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView item = new ImageView(mContext);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            item.setLayoutParams(params);
            ImageUtils.glideImageViewByUrl(mContext, item, editImage.get(position).getUrl());

            container.addView(item);
            return item;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) {
            collection.removeView((View) view);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}
